package com.dmcloud.zuul.config;

import com.dmcloud.zuul.filter.audi.AudiLogFilter;
import com.dmcloud.zuul.ratelimit.GatewayRateLimitFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;

/**
 * Created by xiaodao
 * date: 2020/3/28
 */
@Configuration
@EnableResourceServer
public class GatewaySecurityConfig extends ResourceServerConfigurerAdapter {


    @Autowired
    private GatewayWebSecurityExpressionHandler gatewayWebSecurityExpressionHandler;

    @Autowired
    private GatewayAccessDeniedHandler gatewayAccessDeniedHandler;

    @Autowired
    private GatewayAuthenticationEntryPoint gatewayAuthenticationEntryPoint;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(
                //限流处理器
                new GatewayRateLimitFilter(),
                SecurityContextPersistenceFilter.class)
                //审计过滤器
                .addFilterBefore(new AudiLogFilter(),
                        ExceptionTranslationFilter.class)
                .authorizeRequests()
                .antMatchers("/token/**").permitAll()
                //true能访问 false不能访问 自定义权限过滤器
                .anyRequest().access("#permissionService.hasPermission(request,authentication)");
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //加入自己的
        resources
                //认证失败处理器
                .authenticationEntryPoint(gatewayAuthenticationEntryPoint)
                .accessDeniedHandler(gatewayAccessDeniedHandler)

                .expressionHandler(gatewayWebSecurityExpressionHandler)
        ;
    }
}
